package com.example.mybrowser;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.example.mybrowser.Pack.ResourcePackage;
import com.example.mybrowser.Pack.SerializeHelper;

public class PrefetchConn
{
	static String Android_ID;
	static MobileCache mobileCache;
	public static void getPrefetch() throws HttpException, IOException
	{
		PostMethod post2Server = null;
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(MainActivity.serverIP, MainActivity.serverPort, "http");
		post2Server = new PostMethod("/MyServlet/MyServlet");
		NameValuePair ReqType = new NameValuePair("ReqType", "getPrefetch");
		NameValuePair DevID = new NameValuePair("DevID", Android_ID);
		post2Server.setRequestBody(new NameValuePair[] {ReqType, DevID});
		client.executeMethod(post2Server);
		
		byte[] msg = post2Server.getResponseBody();
	    try
		{
	    	ResourcePackage resPack = SerializeHelper.BytetoPackage(msg);
	    	for (int i=0;i<resPack.Resources.size();i++)
	    	{
	    		if (resPack.Resources.elementAt(i).UseCache!=2)
	    			mobileCache.AddFile(resPack.Resources.elementAt(i));
	    	}
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	public static void setPrefetchinfo(String userSettings) throws HttpException, IOException
	{
		PostMethod post2Server = null;
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(MainActivity.serverIP, MainActivity.serverPort, "http");
		post2Server = new PostMethod("/MyServlet/MyServlet");
		NameValuePair ReqType = new NameValuePair("ReqType", "setPrefetch");
		NameValuePair userset = new NameValuePair("PrefetchInfo", userSettings);
		NameValuePair DevID = new NameValuePair("DevID", Android_ID);
		post2Server.setRequestBody(new NameValuePair[] {ReqType, userset, DevID});
		client.executeMethod(post2Server);
	}
}
